import { message } from 'antd';
import axios, { AxiosError } from 'axios';
import { deleteToken, getToken } from './tokenUtil';
import router from '@/router/router';

const httpInstance = axios.create({
    baseURL: 'http://geek.itheima.net/v1_0',
    timeout: 20000,
});

// 响应类型
export type responseType<T = unknown> = {
    data?: T,
    message?: string,
};

// 请求与响应拦截器
httpInstance.interceptors.request.use(config => {
    // 携带登录token
    const token = getToken();
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
}, error => Promise.reject(error));
httpInstance.interceptors.response.use(response => response.data, (error: AxiosError<responseType>) => {
    if (error.response) {
        const { status, data } = error.response;
        if (status >= 400 && status < 500) {
            // 处理令牌过期事件
            if (status === 401) {
                deleteToken();
                router.navigate('/login');
            }
            message.error(data.message);
        }
    }
    return Promise.reject(error);
});

export { httpInstance };